package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.mapper.DishMapper;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {


    @Autowired
    private DishFlavorService dishFlavorService;

    @Override
    @Transactional
    public boolean saveWithFlavor(DishDto dishDto) {

            //直接把dish的信息添加到dish表中
            this.save(dishDto);
            //获取菜品ID
            Long id=dishDto.getId();
            List<DishFlavor> flavors=dishDto.getFlavors();
            System.out.println(flavors);
            //将口味集合中的所有的菜品id赋值
            for (DishFlavor flavor : flavors) {
                flavor.setDishId(id);
            }
            dishFlavorService.saveBatch(flavors);
            return true;
    }

    @Override
    public DishDto getDtoWithFlavorById(Long id) {
        //根据id得到菜品名单
        Dish dish=this.getById(id);
        DishDto dishDto= new DishDto();
        BeanUtils.copyProperties(dish,dishDto);
                //设置根据id 获得口味集合
        LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper = new LambdaQueryWrapper<DishFlavor>();
        lambdaQueryWrapper.eq(DishFlavor::getDishId,id);
        dishDto.setFlavors(dishFlavorService.list(lambdaQueryWrapper));
        return dishDto;
    }

    @Override
    @Transactional
    public boolean updateWithFlavor(DishDto dishDto) {
        this.updateById(dishDto);
        List<DishFlavor> flavors=dishDto.getFlavors();
        //删除口味表 在 新增口味
        LambdaQueryWrapper<DishFlavor> lqw = new LambdaQueryWrapper<>();
        lqw.eq(DishFlavor::getDishId,dishDto.getId());
        dishFlavorService.remove(lqw);
        //新增口味
        List<DishFlavor> newFlavors=dishDto.getFlavors();
        for (DishFlavor newFlavor : newFlavors) {
            newFlavor.setDishId(dishDto.getId());
        }
        dishFlavorService.saveBatch(newFlavors);
        return true;
    }
}
